#include "Downloader.h"
//#define DEBUG_MODE

MetaCloudDownloader::Downloader::Downloader(string url, string outputFileName) {
	regex eLesson("(?:lesson_id).*?(?=&)");
	regex eCourse("(?:courseid).*?(?=&)");
	string::const_iterator iterStart = url.begin();
	string::const_iterator iterEnd = url.end();
	smatch sm;
	string lessonId, courseId;
	regex_search(iterStart, iterEnd, sm, eLesson);
	lessonId = sm[0].str();
	regex_search(iterStart, iterEnd, sm, eCourse);
	courseId = sm[0].str();

	this->lessonId = lessonId.substr(10);
	this->courseId = courseId.substr(9);
	this->urlBase = "http://metawww.img-cn-hangzhou.aliyuncs.com/courses/" + this->courseId + "/hls/" + this->lessonId + "-";
#ifdef DEBUG_MODE
	cout << "urlBase:" << this->urlBase << endl;
#endif
	this->outputFileName = outputFileName;
}
MetaCloudDownloader::Downloader::~Downloader(void) {

}
void MetaCloudDownloader::Downloader::FetchEachPart(void) {
	char buffer[256];
	for (int i = 1; i <= 100; i++)
	{
		wsprintf(buffer, ".\\tools\\wget %s%05d.ts", this->urlBase.c_str(), i);
#ifdef DEBUG_MODE
		cout << ostr.str() << endl;
#endif
		if (i == 100)
			this->ExecuteCommand(buffer, true);
		else
			this->ExecuteCommand(buffer, false);
		cout << buffer << endl;
	}
}
void MetaCloudDownloader::Downloader::ExecuteCommand(string command, bool isWait) {
	STARTUPINFO si;
	PROCESS_INFORMATION pi;

	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	ZeroMemory(&pi, sizeof(pi));
	if (!CreateProcess(NULL,   // No module name (use command line)
		(char*)command.c_str(),        // Command line
		NULL,           // Process handle not inheritable
		NULL,           // Thread handle not inheritable
		FALSE,          // Set handle inheritance to FALSE
		0,              // No creation flags
		NULL,           // Use parent's environment block
		NULL,           // Use parent's starting directory 
		&si,            // Pointer to STARTUPINFO structure
		&pi)           // Pointer to PROCESS_INFORMATION structure
		)
	{
		printf("CreateProcess failed (%d).\n", GetLastError());
		return;
	}
	if (isWait)
	{
		WaitForSingleObject(pi.hProcess, INFINITE);
	}
}
int MetaCloudDownloader::Downloader::CountParts() {
	system("dir /b/on >lists.txt");
	FILE* fp = fopen("lists.txt", "rb");

	int fileSize = 0;
	while (fgetc(fp) != EOF)
	{
		fileSize++;
	}
	//cnt = 4329;
	char *fileNames;
	//char fileNames[60];
	fileNames = new char[fileSize + 1];
	fclose(fp);
	fp = fopen("lists.txt", "rb");
	for (int i = 0; i < fileSize; i++)
	{
		fileNames[i] = fgetc(fp);
	}
	fileNames[fileSize] = '\0';
	//cout <<cnt<<endl<< fileNames << endl;
	regex eGetId(this->lessonId);
	string files(fileNames);
	string::const_iterator iterStart = files.begin();
	string::const_iterator iterEnd = files.end();
	smatch sm;
	int count = 0;
	while (regex_search(iterStart, iterEnd, sm, eGetId)) {
		iterStart = sm[0].second;
		count++;
	}
	fclose(fp);
	delete[] fileNames;
	this->counts = count;
	return count;
}
void MetaCloudDownloader::Downloader::Merge(void) {
	system("del videolists.txt");
	system("type nul>videolists.txt");
	char buffer[256];
	for (int i = 0; i < this->counts; i++)
	{
		wsprintf(buffer, "echo file '%s-%05d.ts' >> videolists.txt", this->lessonId.c_str(), i + 1);
#ifdef DEBUG_MODE
		cout << buffer << endl;
#endif
		system(buffer);
	}
	this->ExecuteCommand(string(".\\tools\\ffmpeg -f concat -i videolists.txt -c copy ") + this->outputFileName + ".mp4", false);
}
void MetaCloudDownloader::Downloader::DeleteParts(void) {
	char buffer[256];
	for (int i = 0; i < this->counts; i++)
	{
		wsprintf(buffer, "del %s-%05d.ts", this->lessonId.c_str(), i + 1);
#ifdef DEBUG_MODE
		cout << buffer << endl;
#endif
		system(buffer);
	}
}